package com.zr.bookcorner.activity;

import android.os.CountDownTimer;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.widget.ProgressBar;

import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import com.google.android.material.tabs.TabLayout;
import com.zh.baselibrary.base.BaseNoIMActivity;
import com.zh.baselibrary.base.BasePresenter;
import com.zh.baselibrary.constant.ExtraName;
import com.zh.baselibrary.utils.ClickUtils;
import com.zh.baselibrary.utils.IntentUtils;
import com.zh.baselibrary.utils.LogUtils;
import com.zh.baselibrary.utils.TTSUtils;
import com.zh.baselibrary.views.ToastView;
import com.zh.model.manager.BookInfo;
import com.zr.andealib.util.HardEvent;
import com.zr.andealib.util.constant.AndeaConstant;
import com.zr.andealib.util.model.InventoryReport;
import com.zr.bookcorner.R;
import com.zr.bookcorner.adapter.TabPageAdapter;
import com.zr.bookcorner.dialog.BorrowSubmitDialog;
import com.zr.bookcorner.fragment.BorrowReturnDetailFragment;
import com.zr.bookcorner.presenter.BorrowReturnDetailPresenter;
import com.zr.bookcorner.presenter.view.OperateDetailView;
import com.zr.bookcorner.service.VoiceEvent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class BorrowReturnDetailActivity extends BaseNoIMActivity<BorrowReturnDetailPresenter> implements OperateDetailView {
    @BindView(R.id.tabLayout)
    TabLayout mTabLayout;
    @BindView(R.id.viewPager)
    ViewPager mViewPager;
    @BindView(R.id.pb)
    ProgressBar mPb;

    private TabPageAdapter pageAdapter;
    /**
     * 空闲时间
     */
    private static final Long MILLISINFUTURE = (long) 60 * 1000;
    /**
     * 倒计时间隔
     */
    private static final Long COUNTDOWNINTERVAL = (long) 1000;
    private List<Fragment> fragments = new ArrayList<>();
    private String[] mTabNames = new String[]{"柜中书籍", "借阅书籍"};
    private BorrowReturnDetailFragment bookInCabinetFragment;
    private BorrowReturnDetailFragment bookBoorowFragment;
    private List<Integer> mBadgeCountList = new ArrayList<>();

    CountDownTimer countTimer;


    @Override
    protected int getLayoutId() {
        return R.layout.borrow_return_detail_activity;
    }

    @Override
    protected void init() {
        LogUtils.e("开始init");
        EventBus.getDefault().register(this);
        int boxNum = getIntent().getIntExtra(ExtraName.KEY_DATA, -1);
        mPresenter.initDevice(boxNum);
        countTimer = new CountDownTimer(MILLISINFUTURE, COUNTDOWNINTERVAL) {
            @Override
            public void onTick(long millisUntilFinished) {
            }

            @Override
            public void onFinish() {
                mPresenter.toSubmit();
            }
        };
        countTimer.start();
        //初始化2个tab
        bookInCabinetFragment = new BorrowReturnDetailFragment();
        bookBoorowFragment = new BorrowReturnDetailFragment();

        //将提前写好2个Fragment添加到集合中
        fragments.add(bookInCabinetFragment);
        fragments.add(bookBoorowFragment);
        //创建适配器
        mBadgeCountList.add(0);
        mBadgeCountList.add(0);
        pageAdapter = new TabPageAdapter(this, getSupportFragmentManager(), fragments, mTabNames, mBadgeCountList);
        mViewPager.setAdapter(pageAdapter);
        //关联ViewPager
        mTabLayout.setupWithViewPager(mViewPager);
        setUpTabBadge();
        mPresenter.getBorrowRecord();

    }

    @Subscribe(threadMode = ThreadMode.ASYNC)
    public void Event(HardEvent hardEvent) {
        int flag = hardEvent.getFlag();
        if (flag == AndeaConstant.CALL_READ_CHECK_SUCCSES) {
            List<InventoryReport> listTags = (List<InventoryReport>) hardEvent.getData();
            mPresenter.doCheck(listTags);
        } else if (flag == AndeaConstant.CALL_LOCK_STATUS_SUCCSES) {
            mPresenter.openError(1);
        }
    }

    @OnClick({R.id.tv_submit, R.id.iTvTitleLeft})
    public void onClick(View v) {
        if (ClickUtils.isFastClick()) {
            if (v.getId() == R.id.tv_submit) {
                if (mPresenter.isDoorOpen()) {
                    ToastView.showLong("请先关闭柜门，再进行提交");
                } else {
                    showDialog();
                }
            } else {
                if (mPresenter.isDoorOpen()) {
                    ToastView.showLong("请先关闭柜门，再进行返回");
                } else {
                    showDialog();
                }

            }
        }
    }

    public void showDialog() {
        String borrowBookInfo = mPresenter.getName(4);
        String returnBookInfo = mPresenter.getName(5);
        String upBookInfo = mPresenter.getName(1);
        String errorBookInfo = mPresenter.getError();
        countTimer.cancel();
        if (TextUtils.isEmpty(borrowBookInfo + returnBookInfo + upBookInfo + errorBookInfo)) {
            finish();
        } else {
            if (TextUtils.isEmpty(errorBookInfo)) {
                //TTSUtils.getInstance().speak(getString(R.string.to_submit));
                EventBus.getDefault().post(new VoiceEvent(getString(R.string.to_submit)));
            }
            else {
               //TTSUtils.getInstance().speak(getString(R.string.have_error));
                EventBus.getDefault().post(new VoiceEvent(getString(R.string.have_error)));
            }

            BorrowSubmitDialog.DialogListener listener = new BorrowSubmitDialog.DialogListener()
            {
                BorrowReturnDetailPresenter bp;
                @Override
                public void setPresenter(BorrowReturnDetailPresenter bp) {
                    this.bp = bp;
                }

                @Override
                public void submit() {
                    if(bp!=null)
                    bp.toSubmit();
                }

                @Override
                public void mistakes() {
                    if(bp!=null) {
                        countTimer.start();
                        bp.openDoor();
                    }
                }
            };
            listener.setPresenter(mPresenter);

            BorrowSubmitDialog mSubmitDialog = new BorrowSubmitDialog(this,  R.style.DialogTheme,listener);

            mSubmitDialog.show();
            //设置提示信息
            mSubmitDialog.setMessageInfo(borrowBookInfo, returnBookInfo, upBookInfo, errorBookInfo, mPresenter.getErrorSize());
        }

    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_UP) {
            countTimer.start();
        } else {
            countTimer.cancel();
        }
        return super.dispatchTouchEvent(ev);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        countTimer.cancel();
        mPresenter.onDestroy();
    }

    @Override
    public void onSuccess(Object object) {
        IntentUtils.instance().startActivity(this, HomeActivity.class);
    }

    @Override
    public void onHint(String hint) {
        ToastView.showShort(hint);
    }

    @Override
    protected BorrowReturnDetailPresenter createPresenter() {
        return new BorrowReturnDetailPresenter();
    }

    @Override
    public void getDataSuccess(List<BookInfo> data) {
        if (mPb.getVisibility() == View.VISIBLE) {
            mPb.setVisibility(View.GONE);
        }
        bookInCabinetFragment.setDatas(mPresenter.getInList());
        bookBoorowFragment.setDatas(mPresenter.getBookBorrowAllList());
        countTab();
        countTimer.cancel();
        countTimer.start();
    }

    @Override
    public void doorClose() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                showDialog();
            }
        });

    }

    @Override
    public void loading() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (mPb.getVisibility() == View.GONE) {
                    mPb.setVisibility(View.VISIBLE);
                }
            }
        });
    }

    private void countTab() {
        mBadgeCountList.clear();
        mBadgeCountList.add(mPresenter.getUpReturnSize());
        mBadgeCountList.add(mPresenter.getBookBorrowNowList().size());
        setUpTabBadge();

    }

    /**
     * 设置Tablayout上的标题的角标
     */
    private void setUpTabBadge() {
        for (int i = 0; i < fragments.size(); i++) {
            TabLayout.Tab tab = mTabLayout.getTabAt(i);
            // 更新Badge前,先remove原来的customView,否则Badge无法更新
            View customView = tab.getCustomView();
            if (customView != null) {
                ViewParent parent = customView.getParent();
                if (parent != null) {
                    ((ViewGroup) parent).removeView(customView);
                }
            }
            // 更新CustomView
            tab.setCustomView(pageAdapter.getTabItemView(i));
        }

        //需加上以下代码,不然会出现更新Tab角标后,选中的Tab字体颜色不是选中状态的颜色
        mTabLayout.getTabAt(mTabLayout.getSelectedTabPosition()).getCustomView().setSelected(true);

    }

}
